const gaiaManager = require('../../utils/gaiaManager.js').gaiaManager
const bluetoothManager = require('../../utils/bluetooth.js').bluetoothManager

Page({
  data: {
    // 页面状态
    loading: true,
    error: null,
    
    // 演示控制状态（与安卓版本AudioCurationDemoSettings.kt保持一致）
    demoSettings: {
      // ANC状态
      ancState: {
        visible: true,
        enabled: false,
        title: 'Active noise cancellation',
        description: '控制主动降噪功能'
      },
      
      // 媒体播放控制
      mediaPlayback: {
        visible: true,
        enabled: false,
        title: 'Media playback',
        description: '控制媒体播放状态'
      },
      
      // 风噪检测
      windNoiseDetection: {
        visible: true,
        enabled: false,
        title: 'Wind noise detection',
        description: '检测环境风噪'
      },
      
      // 风噪降噪
      windNoiseReduction: {
        visible: true,
        enabled: false,
        title: 'Wind noise reduction',
        description: '降低风噪干扰'
      },
      
      // 自适应功能
      adaptation: {
        visible: true,
        enabled: false,
        title: 'Adaptation',
        description: '自适应音频处理'
      },
      
      // 啸叫检测
      howlingDetection: {
        visible: true,
        enabled: false,
        title: 'Howling detection',
        description: '检测音频啸叫'
      },
      
      // 噪声识别
      noiseIdCategory: {
        visible: true,
        enabled: false,
        title: 'Noise ID',
        description: '识别环境噪声类型',
        category: 'Not applicable'
      },
      
      // 不利声学处理
      adverseAcousticState: {
        visible: true,
        enabled: false,
        title: 'Adverse acoustic handler (AAH)',
        description: '处理不利声学环境'
      }
    },
    
    // 参数调节
    parameters: {
      // 前馈增益
      feedForwardGain: {
        visible: true,
        title: 'Feed forward gain',
        value: 0,
        min: -20,
        max: 20,
        unit: 'dB'
      },
      
      // 泄漏增益
      leakthroughGain: {
        visible: true,
        title: 'Leakthrough gain',
        value: 0,
        min: -20,
        max: 20,
        unit: 'dB'
      },
      
      // 左右平衡
      leftRightBalance: {
        visible: true,
        title: 'Left right balance',
        value: 50,
        min: 0,
        max: 100,
        unit: '%'
      },
      
      // 反馈增益
      feedbackGain: {
        visible: true,
        title: 'Feedback gain',
        value: 0,
        min: -20,
        max: 20,
        unit: 'dB'
      }
    },
    
    // 演示状态
    demoActive: false,
    
    // 状态信息
    statusInfo: {
      windDetectionStatus: 'Not detected',
      howlingDetectionStatus: 'Not detected',
      adverseAcousticStatus: 'Not enabled'
    }
  },

  onLoad(options) {
    console.log('音频管理演示页面加载')
    this.loadDemoData()
  },

  onShow() {
    if (bluetoothManager.isConnected) {
      this.loadDemoData()
    }
  },

  // 加载演示数据
  async loadDemoData() {
    if (!bluetoothManager.isConnected) {
      wx.showToast({
        title: '设备未连接',
        icon: 'error'
      })
      return
    }

    this.setData({ loading: true, error: null })

    try {
      // 获取音频管理演示支持状态
      const supportResponse = await gaiaManager.getAudioCurationDemoSupport()
      console.log('音频管理演示支持状态:', supportResponse)

      if (supportResponse.supported) {
        // 获取当前状态
        await this.loadCurrentStates()
      } else {
        this.setData({
          error: '设备不支持音频管理演示功能'
        })
      }
    } catch (error) {
      console.error('加载演示数据失败:', error)
      this.setData({
        error: '加载数据失败: ' + error.message
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 加载当前状态
  async loadCurrentStates() {
    try {
      // 获取ANC状态
      const ancState = await gaiaManager.getANCState()
      if (ancState.success) {
        this.setData({
          'demoSettings.ancState.enabled': ancState.data.enabled
        })
      }

      // 获取噪声识别状态
      const noiseIdState = await gaiaManager.getNoiseIdState()
      if (noiseIdState.success) {
        this.setData({
          'demoSettings.noiseIdCategory.enabled': noiseIdState.data.enabled
        })
      }

      // 获取啸叫检测状态
      const howlingState = await gaiaManager.getHowlingDetectionState()
      if (howlingState.success) {
        this.setData({
          'demoSettings.howlingDetection.enabled': howlingState.data.enabled
        })
      }

      // 获取噪声分类
      const noiseCategory = await gaiaManager.getNoiseIdCategory()
      if (noiseCategory.success) {
        this.setData({
          'demoSettings.noiseIdCategory.category': this.getNoiseCategoryText(noiseCategory.data.category)
        })
      }

    } catch (error) {
      console.error('加载当前状态失败:', error)
    }
  },

  // ANC状态改变
  async onAncStateChange(e) {
    const enabled = e.detail.value
    this.setData({
      'demoSettings.ancState.enabled': enabled
    })

    try {
      await gaiaManager.setANCState(enabled)
      wx.showToast({
        title: enabled ? 'ANC已启用' : 'ANC已禁用',
        icon: 'success'
      })
    } catch (error) {
      console.error('设置ANC状态失败:', error)
      this.setData({
        'demoSettings.ancState.enabled': !enabled
      })
      wx.showToast({
        title: '设置失败',
        icon: 'error'
      })
    }
  },

  // 媒体播放控制
  async onMediaPlaybackChange(e) {
    const enabled = e.detail.value
    this.setData({
      'demoSettings.mediaPlayback.enabled': enabled
    })

    try {
      if (enabled) {
        await gaiaManager.mediaPlay()
        wx.showToast({
          title: '媒体播放已开始',
          icon: 'success'
        })
      } else {
        await gaiaManager.mediaPause()
        wx.showToast({
          title: '媒体播放已暂停',
          icon: 'success'
        })
      }
    } catch (error) {
      console.error('媒体播放控制失败:', error)
      this.setData({
        'demoSettings.mediaPlayback.enabled': !enabled
      })
      wx.showToast({
        title: '控制失败',
        icon: 'error'
      })
    }
  },

  // 风噪检测
  async onWindNoiseDetectionChange(e) {
    const enabled = e.detail.value
    this.setData({
      'demoSettings.windNoiseDetection.enabled': enabled,
      'statusInfo.windDetectionStatus': enabled ? 'Detecting' : 'Not detected'
    })

    try {
      // 这里应该调用风噪检测相关的GAIA命令
      wx.showToast({
        title: enabled ? '风噪检测已启用' : '风噪检测已禁用',
        icon: 'success'
      })
    } catch (error) {
      console.error('风噪检测控制失败:', error)
      this.setData({
        'demoSettings.windNoiseDetection.enabled': !enabled
      })
      wx.showToast({
        title: '控制失败',
        icon: 'error'
      })
    }
  },

  // 风噪降噪
  async onWindNoiseReductionChange(e) {
    const enabled = e.detail.value
    this.setData({
      'demoSettings.windNoiseReduction.enabled': enabled
    })

    try {
      // 这里应该调用风噪降噪相关的GAIA命令
      wx.showToast({
        title: enabled ? '风噪降噪已启用' : '风噪降噪已禁用',
        icon: 'success'
      })
    } catch (error) {
      console.error('风噪降噪控制失败:', error)
      this.setData({
        'demoSettings.windNoiseReduction.enabled': !enabled
      })
      wx.showToast({
        title: '控制失败',
        icon: 'error'
      })
    }
  },

  // 自适应功能
  async onAdaptationChange(e) {
    const enabled = e.detail.value
    this.setData({
      'demoSettings.adaptation.enabled': enabled
    })

    try {
      // 这里应该调用自适应相关的GAIA命令
      wx.showToast({
        title: enabled ? '自适应已启用' : '自适应已禁用',
        icon: 'success'
      })
    } catch (error) {
      console.error('自适应控制失败:', error)
      this.setData({
        'demoSettings.adaptation.enabled': !enabled
      })
      wx.showToast({
        title: '控制失败',
        icon: 'error'
      })
    }
  },

  // 啸叫检测
  async onHowlingDetectionChange(e) {
    const enabled = e.detail.value
    this.setData({
      'demoSettings.howlingDetection.enabled': enabled,
      'statusInfo.howlingDetectionStatus': enabled ? 'Detecting' : 'Not detected'
    })

    try {
      await gaiaManager.setHowlingDetectionState(enabled)
      wx.showToast({
        title: enabled ? '啸叫检测已启用' : '啸叫检测已禁用',
        icon: 'success'
      })
    } catch (error) {
      console.error('啸叫检测控制失败:', error)
      this.setData({
        'demoSettings.howlingDetection.enabled': !enabled
      })
      wx.showToast({
        title: '控制失败',
        icon: 'error'
      })
    }
  },

  // 噪声识别
  async onNoiseIdChange(e) {
    const enabled = e.detail.value
    this.setData({
      'demoSettings.noiseIdCategory.enabled': enabled
    })

    try {
      await gaiaManager.setNoiseIdState(enabled)
      wx.showToast({
        title: enabled ? '噪声识别已启用' : '噪声识别已禁用',
        icon: 'success'
      })
    } catch (error) {
      console.error('噪声识别控制失败:', error)
      this.setData({
        'demoSettings.noiseIdCategory.enabled': !enabled
      })
      wx.showToast({
        title: '控制失败',
        icon: 'error'
      })
    }
  },

  // 不利声学处理
  async onAdverseAcousticChange(e) {
    const enabled = e.detail.value
    this.setData({
      'demoSettings.adverseAcousticState.enabled': enabled,
      'statusInfo.adverseAcousticStatus': enabled ? 'Enabled' : 'Not enabled'
    })

    try {
      // 这里应该调用不利声学处理相关的GAIA命令
      wx.showToast({
        title: enabled ? '不利声学处理已启用' : '不利声学处理已禁用',
        icon: 'success'
      })
    } catch (error) {
      console.error('不利声学处理控制失败:', error)
      this.setData({
        'demoSettings.adverseAcousticState.enabled': !enabled
      })
      wx.showToast({
        title: '控制失败',
        icon: 'error'
      })
    }
  },

  // 参数调节
  onParameterChange(e) {
    const { parameter, value } = e.detail
    this.setData({
      [`parameters.${parameter}.value`]: value
    })

    // 这里应该调用相应的GAIA命令来设置参数
    console.log(`设置${parameter}参数:`, value)
  },

  // 开始演示
  async startDemo() {
    if (!bluetoothManager.isConnected) {
      wx.showToast({
        title: '设备未连接',
        icon: 'error'
      })
      return
    }

    try {
      await gaiaManager.setAudioCurationDemoState(true)
      this.setData({ demoActive: true })
      
      wx.showToast({
        title: '演示已开始',
        icon: 'success'
      })
    } catch (error) {
      console.error('开始演示失败:', error)
      wx.showToast({
        title: '开始演示失败',
        icon: 'error'
      })
    }
  },

  // 停止演示
  async stopDemo() {
    try {
      await gaiaManager.setAudioCurationDemoState(false)
      this.setData({ demoActive: false })
      
      wx.showToast({
        title: '演示已停止',
        icon: 'success'
      })
    } catch (error) {
      console.error('停止演示失败:', error)
      wx.showToast({
        title: '停止演示失败',
        icon: 'error'
      })
    }
  },

  // 重置参数
  resetParameters() {
    this.setData({
      'parameters.feedForwardGain.value': 0,
      'parameters.leakthroughGain.value': 0,
      'parameters.leftRightBalance.value': 50,
      'parameters.feedbackGain.value': 0
    })

    wx.showToast({
      title: '参数已重置',
      icon: 'success'
    })
  },

  // 获取噪声分类文本
  getNoiseCategoryText(category) {
    switch (category) {
      case 0:
        return 'Category A'
      case 1:
        return 'Category B'
      case 255:
        return 'Not applicable'
      default:
        return 'Undefined category: ' + category
    }
  },

  // 重试加载
  retryLoad() {
    this.loadDemoData()
  }
})

